//职员管理

import React, {Component} from 'react';
import app from '../app';
import {Form, Input, Button, Table, Modal, Row, Upload, Icon, DatePicker, Select, Pagination} from 'antd';
import {project, invitation} from '../value';
import '../css/other.css';
import moment from 'moment';
import {config} from "../config";
import {AddInvitationActivitys, EditInvitationActivitys, CustomerLists} from '../components/operateManage';

import {Editor} from 'react-draft-wysiwyg';

const FormItem = Form.Item;
const confirm = Modal.confirm;
const RangePicker = DatePicker.RangePicker;
const Option = Select.Option;

class Invitation extends Component {
    constructor(props) {
        super(props);
        this.state = {
            searchData: {},
            pagination: {current: 1, pageSize: 10, total: 0},
            data: [],
            currentPageSize: 0,
            pageCount: 0,
            imgUrl: '',
        }
    }

    columns = [
        {
            title: '序号',
            dataIndex: 'order_number'
        },
        {
            title: '标题',
            dataIndex: 'invitation_name'
        },
        {
            title: '类型',
            dataIndex: 'invitation_type',
            render: type => {
                let text = '';
                if (type === '1') {
                    text = '消费邀请奖励';
                } else if (type === '2') {
                    text = '注册邀请奖励';
                }
                return (
                    <span>{text}</span>
                )
            }
        },
        {
            title: '奖励金额',
            dataIndex: 'invitation_reward'
        },
        {
            title: '开始结束时间',
            dataIndex: this.columns,
            render: data => {
                return (
                    <span>{moment(data.invitation_startTime).format('YYYY-MM-DD')}至{moment(data.invitation_endTime).format('YYYY-MM-DD')}</span>
                )
            }
        },
        {
            title: '状态',
            dataIndex: 'invitation_status',
            render: invitation_status => {
                let text = '';
                if (invitation_status === '1') {
                    text = '未开始';
                } else if (invitation_status === '2') {
                    text = '进行中';
                } else if (invitation_status === '3') {
                    text = '已结束';
                } else if (invitation_status === '4') {
                    text = '已停用';
                }
                return (
                    <span>{text}</span>
                )
            }
        },
        {
            title: '已邀请人数',
            render: data => {
                return (
                    <CustomerLists num={data.number} id={data.invitation_id}></CustomerLists>
                )
            }
        },
        {
            title: '已奖励金额',
            dataIndex: 'price'
        },
        {
            title: '说明',
            dataIndex: 'invitation_explain'
        },
        {
            title: '操作',
            dataIndex: this.columns,
            render: data => {
                return (
                    <div>
                        <EditInvitationActivitys data={data}
                                                 refresh={() => this.handleRefreshAfterUpdate()}></EditInvitationActivitys>
                        {
                            data.invitation_isable === '1' ? <Button style={{marginLeft: '10px'}} type="danger"
                                                                     onClick={() => this.handleUpdateInvitationIsAble(data, 0)}>停用</Button> :
                                <Button style={{marginLeft: '10px'}} type="primary"
                                        onClick={() => this.handleUpdateInvitationIsAble(data, 1)}>启用</Button>
                        }
                        <Button style={{marginLeft: '10px'}} type="danger"
                                onClick={() => this.handleUpdateInvitationIsAble(data, 2)}>删除</Button>
                    </div>
                )
            }
        },
    ];

    render() {
        const rowSelection = {
            // 表格中复选框发生变化时
            onChange: (selectedRowKeys, selectedRows) => {
                let positionId = [];
                let positionName = [];
                positionId = selectedRowKeys;
                selectedRows.forEach((item) => {
                    positionName.push(item.role_name);
                });
                this.setState({
                    positionId: positionId,  //批量选中的职位ID
                    positionName: positionName,
                    selectCount: selectedRowKeys.length, //一共选择的职位数量
                })
            },

        };
        return (
            <div style={{paddingBottom: 25}}>
                <div className="pageTitle">
                    邀请奖励
                </div>
                <SearchLists refresh={() => this.handleRefreshAfterCreate()}
                             clickSearch={(values) => this.handleGetValue(values)}/>
                <Row style={{marginTop: '20px'}}>
                    <Table
                        columns={this.columns}
                        rowKey={(record, index) => index}
                        dataSource={this.state.data}
                        loading={this.state.loading}
                        pagination={false}
                        onChange={this.handleTableChange}
                    />
                </Row>
                <Row style={{textAlign: 'right', marginTop: 20}}>
                    <Pagination {...this.state.pagination} showSizeChanger showQuickJumper
                                onChange={(page, pageSize) => this.handleOnChange(page, pageSize)}
                                onShowSizeChange={(current, size) => this.handleOnShowSizeChange(current, size)}/>
                </Row>
            </div>
        )
    }

    /**
     * 初始化
     */
    componentDidMount() {
        let param = {page: 1, size: 10};
        this.searchInvitationList(param);
    }

    /**
     * 获取搜索条件
     */
    handleGetValue(param) {
        let startTime1 = '', endTime1 = '', endTime2 = '', startTime2 = '';
        let {typeSearch, statusSearch, dateTime1, dateTime2} = param;
        if (dateTime1 && dateTime1.length > 0) {
            startTime1 = moment(dateTime1[0]._d).format('YYYY-MM-DD HH:mm:ss');
            endTime1 = moment(dateTime1[1]._d).format('YYYY-MM-DD HH:mm:ss');
        }
        if (dateTime2 && dateTime2.length > 0) {
            startTime2 = moment(dateTime2[0]._d).format('YYYY-MM-DD HH:mm:ss');
            endTime2 = moment(dateTime2[1]._d).format('YYYY-MM-DD HH:mm:ss');
        }
        const searchData = {
            typeSearch,
            statusSearch,
            startTime1,
            endTime1,
            startTime2,
            endTime2
        };
        // const searchData = {project_name: value};
        this.setState({searchData});
        const param1 = {
            page: 1,
            size: 10,
            ...searchData
        };
        this.searchInvitationList(param1);
    }

    /**
     * 处理创建后刷新事件
     */
    handleRefreshAfterCreate() {
        const {searchData} = this.state;
        const param = {
            page: 1,
            size: 10,
            ...searchData
        };
        this.searchInvitationList(param);
    }

    /**
     * 处理删除后刷新事件
     */
    handleRefreshAfterDelete() {
        const {searchData} = this.state;
        const param = {
            page: 1,
            size: 10,
            ...searchData
        };
        this.searchInvitationList(param);
    }

    /**
     * 处理更新后刷新事件
     */
    handleRefreshAfterUpdate() {
        const {searchData, pagination} = this.state;
        const param = {
            page: pagination.current,
            size: pagination.pageSize,
            ...searchData
        };
        this.searchInvitationList(param);
    }

    /**
     * 处理页码、显示数量变化事件
     * @param pagination
     * @param filters
     * @param sorter
     */
    handleTableChange = (pagination, filters, sorter) => {
        const current = pagination.current;
        const size = pagination.pageSize;
        const pagination1 = this.state.pagination;
        pagination1.current = current;
        pagination1.pageSize = size;
        this.setState({pagination: pagination1});
    };

    /**
     * 处理页面改变事件
     * @param page
     * @param pageSize
     */
    handleOnChange(page, pageSize) {
        const {searchData} = this.state;
        const param = {
            page,
            size: pageSize,
            ...searchData
        };
        this.searchInvitationList(param);
    }

    /**
     * 处理pageSize变化回调
     * @param current
     * @param size
     */
    handleOnShowSizeChange(current, size) {
        const {searchData} = this.state;
        const param = {
            page: current,
            size,
            ...searchData
        };
        this.searchInvitationList(param);
    }

    /**
     * 查找邀请奖励列表
     * @param param
     */
    searchInvitationList(param) {
        let _this = this;
        _this.setState({loading: true});
        app.post(invitation.SEARCH_INVITATION_LIST, param).then(result => {
            if (result.code === 1) {
                const data = result.data;
                for (let i = 0; i < data.length; i++) {
                    data[i].order_number = i + 1;
                }
                const pagination = {total: result.count, current: param.page, pageSize: param.size};
                _this.setState({pagination, data: data, loading: false});
            } else {
                app.alert(result.msg, 'success', 2);
                const pagination = {total: 0, current: 0, pageSize: 0};
                _this.setState({pagination, data: [], loading: false});
            }
        });
    }

    /**
     * 编辑邀请项目状态
     * @param id
     */
    handleUpdateInvitationIsAble(data, type) {
        let {invitation_id,invitation_type,invitation_startTime,invitation_endTime}=data;
        invitation_endTime=moment(invitation_endTime).format('YYYY-MM-DD HH:mm:ss');
        invitation_startTime=moment(invitation_startTime).format('YYYY-MM-DD HH:mm:ss');
        let param={
            invitation_id,
            invitation_isable:type.toString(),
            invitation_type,
            invitation_startTime,
            invitation_endTime
        };
        let _this = this;
        if (type === 2) {
            confirm({
                content: '您确定要删除该邀请吗？',
                onOk() {
                    app.post(invitation.UPDATE_INVITATION_ISABLE, param).then((req) => {
                        if (req.code === 1) {
                            app.alert("删除成功", 'success', 1);
                            _this.handleRefreshAfterDelete();
                        } else {
                            app.alert(req.msg, 'error', 1);
                        }
                    })
                },
                onCancel() {
                },
            });
        } else if (type === 0) {
            confirm({
                content: '您确定要停用该邀请吗？',
                onOk() {
                    app.post(invitation.UPDATE_INVITATION_ISABLE, param).then((req) => {
                        if (req.code === 1) {
                            app.alert("停用成功", 'success', 1);
                            _this.handleRefreshAfterUpdate();
                        } else {
                            app.alert(req.msg, 'error', 1);
                        }
                    })
                },
                onCancel() {
                },
            });
        } else if (type === 1) {
            app.post(invitation.UPDATE_INVITATION_ISABLE, param).then((req) => {
                if (req.code === 1) {
                    app.alert("启用成功", 'success', 1);
                    _this.handleRefreshAfterUpdate();
                } else {
                    app.alert(req.msg, 'error', 1);
                }
            })
        }
    }
}


class SearchList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            project_name: '',
            typeList: [
                {
                    id: '01',
                    name: '会员注册奖励'
                }
            ]
        }
    };

    render() {
        const {getFieldDecorator} = this.props.form;
        const dateFormat = 'YYYY-MM-DD';
        return (
            <div style={{display: 'flex', marginTop: 10, marginBottom: 5}}>
                <div style={{display: 'flex', width: '150px', height: '28px'}}>
                    <div style={{width: 50, height: 28, lineHeight: '28px', color: '#000000'}}>类型：</div>
                    <Select style={{width: 100}} placeholder={'请选择类型'} onChange={(e) => this.handleTypeOnChange(e)}>
                        <Option value={'1'}>消费邀请奖励</Option>
                        <Option value={'2'}>注册邀请奖励</Option>
                    </Select>
                </div>
                <div style={{display: 'flex', width: '310px', height: '28px', marginLeft: 10}}>
                    <div style={{width: 100, height: 28, lineHeight: '28px', color: '#000000'}}>活动开始时间：</div>
                    <RangePicker format={dateFormat} style={{width: 210}}
                                 onChange={(e) => this.handleDateTime1OnChange(e)}/>
                </div>
                <div style={{display: 'flex', width: '310px', height: '28px', marginLeft: 10}}>
                    <div style={{width: 100, height: 28, lineHeight: '28px', color: '#000000'}}>活动结束时间：</div>
                    <RangePicker format={dateFormat} style={{width: 210}}
                                 onChange={(e) => this.handleDateTime2OnChange(e)}/>
                </div>
                <div style={{display: 'flex', width: '170px', height: '28px', marginLeft: 10}}>
                    <div style={{width: 60, height: 28, lineHeight: '28px', color: '#000000'}}>活动状态：</div>
                    <Select style={{width: 110}} placeholder={'请选择状态'} onChange={(e) => this.handleStatusOnchange(e)}>
                        <Option value="1">未开始</Option>
                        <Option value="2">进行中</Option>
                        <Option value="3">已结束</Option>
                        <Option value="4">已停用</Option>
                    </Select>
                </div>
                <div style={{display: 'flex', width: '120px', height: '28px', marginLeft: 20}}>
                    <Button type="primary" onClick={() => this.handleSearchComplain1()}>搜索</Button>
                    <AddInvitationActivitys refresh={() => this.handleRefreshAfterCreate()}></AddInvitationActivitys>
                </div>
            </div>
        )
    };

    componentDidMount() {
    };

    /**
     * 处理类型选择变化事件
     * @param e
     */
    handleTypeOnChange(e) {
        this.setState({typeSearch: e});
        let {dateTime1, dateTime2, statusSearch} = this.state;
        const param = {
            statusSearch,
            dateTime1,
            dateTime2,
            typeSearch: e
        };
        this.props.clickSearch(param);
    }

    /**
     * 处理活动开始时间选择变化事件
     * @param e
     */
    handleDateTime1OnChange(e) {
        this.setState({dateTime1: e});
        let {typeSearch, dateTime2, statusSearch} = this.state;
        const param = {
            statusSearch,
            dateTime1: e,
            dateTime2,
            typeSearch
        };
        this.props.clickSearch(param);
    }

    /**
     * 处理活动结束时间选择变化事件
     * @param e
     */
    handleDateTime2OnChange(e) {
        this.setState({dateTime2: e});
        let {typeSearch, dateTime1, statusSearch} = this.state;
        const param = {
            statusSearch,
            dateTime1,
            dateTime2: e,
            typeSearch
        };
        this.props.clickSearch(param);
    }

    /**
     * 处理状态选择变化事件
     * @param e
     */
    handleStatusOnchange(e) {
        this.setState({statusSearch: e});
        let {dateTime1, dateTime2, typeSearch} = this.state;
        const param = {
            typeSearch,
            dateTime1,
            dateTime2,
            statusSearch: e
        };
        this.props.clickSearch(param);
    }

    /**
     * 获取搜索条件
     */
    handleSearchComplain1() {
        let {dateTime1, dateTime2, typeSearch, statusSearch} = this.state;
        const param = {
            typeSearch,
            dateTime1,
            dateTime2,
            statusSearch
        };
        this.props.clickSearch(param);
    };

    handleRefreshAfterCreate() {
        this.props.refresh();
    }
}

const SearchLists = Form.create()(SearchList);
const Invitations = Form.create()(Invitation);

export default Invitations


